<template>
  <div class="login-container">
    <div class="login-box">
      <h2>管理员登录</h2>
      <form @submit.prevent="handleLogin">
        <div class="input-group">
          <label>账号:</label>
          <input
              v-model="form.username"
              type="text"
              placeholder="请输入管理员账号"
              required
              :disabled="authStore.loading"
          >
        </div>
        <div class="input-group">
          <label>密码:</label>
          <input
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
              required
              :disabled="authStore.loading"
              @keyup.enter="handleLogin"
          >
        </div>
        <button
            type="submit"
            class="login-btn"
            :disabled="authStore.loading || !form.username || !form.password"
        >
          {{ authStore.loading ? '登录中...' : '登录' }}
        </button>

        <div v-if="error" class="error-message">
          {{ error }}
        </div>

        <div class="demo-account">
          <p><strong>管理员账号：</strong></p>
          <p>admin / 123456</p>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const router = useRouter()
const authStore = useAuthStore()
const error = ref('')
const loading = ref(false)

const form = reactive({
  username: '',
  password: ''
})

onMounted(() => {
  authStore.initialize()
})

const handleLogin = async () => {
  error.value = ''
  loading.value = true

  if (!form.username || !form.password) {
    error.value = '请填写账号和密码'
    loading.value = false
    return
  }

  try {
    // ✅ 使用管理员登录接口（使用相对路径，通过vite代理）
    const response = await axios.post('/api/admin/login', {
      username: form.username,
      password: form.password
    })

    console.log('登录响应:', response.data) // 调试用

    if (response.data && response.data.success) {
      // 保存token和用户信息
      const { token, user } = response.data
      localStorage.setItem('token', token)
      localStorage.setItem('user', JSON.stringify(user))
      
      console.log('保存的Token:', token) // 调试用
      console.log('保存的用户信息:', user) // 调试用

      // 更新store状态
      authStore.isLoggedIn = true
      authStore.user = user

      ElMessage.success('登录成功')

      // 登录成功，跳转到首页
      setTimeout(() => {
        router.push('/')
      }, 500)
    } else {
      error.value = response.data?.message || '登录失败'
    }
  } catch (err) {
    console.error('登录错误详情:', err) // 调试用
    error.value = err.response?.data?.message || '登录失败，请检查网络连接'
  } finally {
    loading.value = false
  }
}
</script>

<!-- 样式部分保持不变 -->
<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-box {
  background: white;
  padding: 40px;
  border-radius: 10px;
  width: 400px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
}

.input-group {
  margin-bottom: 20px;
}

.input-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #555;
}

.input-group input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 16px;
  transition: border-color 0.3s;
  box-sizing: border-box;
}

.input-group input:focus {
  outline: none;
  border-color: #667eea;
}

.input-group input:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.login-btn {
  width: 100%;
  padding: 12px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
  transition: background 0.3s;
  margin-top: 10px;
}

.login-btn:hover:not(:disabled) {
  background: #5a6fd8;
}

.login-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.error-message {
  color: #e74c3c;
  text-align: center;
  margin-top: 15px;
  padding: 10px;
  background: #ffeaea;
  border-radius: 5px;
}

.demo-account {
  margin-top: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 5px;
  text-align: center;
  color: #666;
  font-size: 14px;
}

.demo-account p {
  margin: 5px 0;
}
</style>